package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaAnalysisService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Resource
    WxMaService wxMaService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    UserAccountFeignClient userAccountFeignClient;


    @GlobalTransactional
    @Override
    public Map<String, String> wxLogin(String code) throws WxErrorException {

        WxMaJscode2SessionResult sessionInfo = this.wxMaService.getUserService().getSessionInfo(code);
        String openid = null;
        if (sessionInfo != null) {
            openid = sessionInfo.getOpenid();
        }
        if (StringUtils.isBlank(openid)) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
// 查询数据库
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<>(UserInfo.class).eq(UserInfo::getWxOpenId, openid));
        // 判断数据用户是否存在
        if (userInfo == null) {
            // 隐私注册
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("这家伙有点帅-过头" + IdWorker.getIdStr()); // 雪花算法生成唯一标识
            userInfo.setAvatarUrl("https://ww1.sinaimg.cn/mw690/9516662fgy1hct88xfrd9j20k00k0dho.jpg");
            userInfo.setStatus("1");
            this.save(userInfo);

            // 初始化账户
            this.userAccountFeignClient.saveAmount(userInfo.getId());
//            int i = 1/0  ;
        }
        // 用户存在 以token为键 用户信息为值 缓存到Redis中
        String token = UUID.randomUUID().toString();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
         this.redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+ token,userInfoVo);


        Map<String, String> map = new HashMap<>();
        map.put("token",token);
        return map;
    }
}
